// import Vue from 'vue';
const fs = require('fs');
const path = require('path');
function resolve(dir) {
  return path.join(__dirname, dir)
}
Date.prototype.format = function(fmt) { // author: meizz
  var o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'h+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    'S': this.getMilliseconds()
    // 毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 -
            RegExp.$1.length));
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ?
        (o[k]) :
        (('00' + o[k]).substr(('' + o[k]).length)));
  return fmt;
};

var ComsUtil = {};
if (typeof require.context === 'undefined') {
  require.context = (base = '.', scanSubDirectories = false, regularExpression = /\.js$/) => {
    const files = {};

    function readDirectory(directory) {
      fs.readdirSync(directory).forEach((file) => {
        const fullPath = path.resolve(directory, file);

        if (fs.statSync(fullPath).isDirectory()) {
          if (scanSubDirectories) readDirectory(fullPath);

          return;
        }

        if (!regularExpression.test(fullPath)) return;

        files[fullPath] = true;
      });
    }

    readDirectory(path.resolve(__dirname, base));

    function Module(file) {
      return require(file);
    }

    Module.keys = () => Object.keys(files);

    return Module;
  };
}

function __createLink(src, id, callback) {
  let link = document.getElementById('#' + id);
  if (!document.getElementById('#' + id)) {
    link = document.createElement('link');
    link.id = id;
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = src;
    link.onload = function linkLoad() {
      if (callback) {
        callback();
      }
    }
    link.onerror = function linkError() {
      if (callback) {
        callback();
      }
    }
    document.head.appendChild(link);
  } else {
    link.href = src;
  }

}

ComsUtil.remoteRequire =  function(list) {
  var d = [{
    'id': 28,
    'menuName': '菜单管理',
    'parentId': 0,
    'sortIndex': 1,
    'path': 'MenuManage',
    'componentCss': 'MenuManage.css',
    'componentFile': 'MenuManage.umd.js',
    'component': '/api/static/lib/MenuManage/',
    'menuType': 'L',
    'icon': '',
    'children': [],
    'file': null,
    'cssFile': null,
    'frame': false
  }];
  const modules = {};
  list.forEach(async(e) => {
    switch (e.menuType) {
    case 'M':
      try {
        if (e.componentCss) {
          require(`@/module/${e.path}.css`);
        }
        let mo = require(`@/module/${e.path}.umd.js`);
        modules[e.path] = mo.default || mo;
        Vue.component(e.path, modules[e.path]);
      } catch (err) {
        console.error(e.path, e.component, err)
      }

      break;
    case 'L':
      // 异步加载模块如果使用同步的话modules可用
      // Vue.component(e.path, function(resolve, reject) {
      //   // 异步加载模块如果使用同步的话modules可用
      //   var XML = new XMLHttpRequest();
      //   XML.open('GET', e.component + e.componentFile, false);
      //   XML.send();
      //   if (XML.status == 200) {
      //     // 执行以下js 字符串
      //     modules[e.path] = new Function(XML.responseText)();
      //     __createLink(e.component + e.componentCss, e.path);
      //     // 重点注意一下resolve
      //     // window[e.path]
      //     resolve(global[e.path])
      //   }
      // });

      if (modules[e.path]) break;
      // 同步加载模块如果异步加载，当前不可用
      console.info('加载资源:'+e.path);
      $.ajax({
        url: e.component + '?' + e.version,
        type: 'GET',
        async: false,
        success(data) {
          try {
            new Function(data)();
            Vue.component(e.path, (resolve, reject) => {
              $.ajax({
                url: e.component+'?'+e.version,
                type: 'GET',
                async: false,
                success(data) {
                  var regex2 = /(?<=define\(\[)(.+?)(?=\])/g;
                  // /\[(.+?)\]/g;   // [] 中括号
                  var l = data.match(regex2);
                  if (l) {
                    let cms = l[0].split(',');

                    for (let i = 0; i < cms.length; i++) {
                      try {
                        const k = cms[i].replaceAll('\"', '').replace(/\s/g, '');
                        const p =k.replace('@/', '');
                        window[k] = global[k] =  require('@/' + p);
                        console.info('加载依赖组件', k, p)
                      } catch (e) {
                        console.error('依赖组件加载失败..', cms[i], e);
                      }
                    }
                  }
                  if (e.componentCss) {
                    __createLink(e.componentCss, e.path);
                  }
                  try {
                    new Function(data)();
                    // 执行以下js 字符串
                    modules[e.path] = window[e.component];
                    // 重点注意一下resolve
                    // window[e.path]
                    resolve(global[e.path])
                  } catch (e) {
                    reject(false);
                  }
                }
              });
            });
          } catch (e) {
          }
        }
      });
      break;
    }
  });
  return modules;
}

ComsUtil.localRequire = function(data) {
  const modules = {};
  const files = require.context('../components/module/', true, /index.vue$/);
  var names = [];
  files.keys().forEach(key => {
    console.info('文件真实路径:', key)
    let pathArry = key.split('/');
    let name='';
    if (pathArry.length>3) {
      let ns =[];
      for (let i = 1; i < pathArry.length-1; i++) {
        ns.push(pathArry[i]);
      }
      name=ns.join('/');
    } else {
      name = pathArry[1];
    }

    if (!name) return;
    names.push(name);
    const componentConfig = files(key);
    modules[name] = componentConfig.default || componentConfig;
    Vue.component(name, modules[name]);
  });
  console.log(
    '\x1B[32m%s\x1B[45m',
    'module模块key值:' + JSON.stringify(names)
  );
  return modules;
};

export default ComsUtil;
